<?php

namespace app\common\service;


use app\common\model\banxi\Sms;
use app\common\service\aliyun\AliyunSmsService;
use ba\Random;


class SmsService extends ApiService
{

    /**
     * 事件列表
     * @var array|string[]
     */
    private array $eventList = [
        'userLogin' => '学员端验证码登录',
        'userForgotPassword' => '学员端忘记密码',
        'userUpdatePassword' => '学员端修改密码'

    ];

    /**
     * 验证码有效时长(秒)
     * @var int
     */
    protected int $expire = 120;

    /**
     * 最大允许检测的次数
     * @var int
     */
    protected int $maxCheckNums = 10;

    /**
     * 发送短信
     * @param string $phone 手机号
     * @param string $code 验证码
     * @return bool
     */
    public function sendSms(string $phone, string|null $code): bool
    {
        $code = is_null($code) ? Random::build('numeric', 6) : $code;
        // 使用阿里云短信服务
        $aliyunSmsService = new AliyunSmsService();
        $res = $aliyunSmsService->sendSms($phone, $code);
        if ($res['code'] != 0) {
            $this->setError($res['msg']);
            return false;
        }
        return true;
    }

    /**
     * 验证短信验证码
     * @param string $phone 手机号
     * @param string $code 验证码
     * @param string $event 事件
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function verifySms(string $phone, string $code, string $event): bool
    {
        if (!$this->getEvent($event)) {
            return false;
        }
        $ip = request()->ip();
        $where = [
            'mobile' => $phone,
            'event' => $event,
            'ip' => $ip
        ];
        $smsInfo = Sms::where($where)->order('id', 'desc')->find();
        //判断是否存在
        if (empty($smsInfo)) {
            $this->setError('Captcha error');
            return false;
        }

        $time = time() - $this->expire;
        //判断错误次数是否超过最大次数
        $createTime = $smsInfo['createTime'];
        if ($createTime < $time){
            $this->flush($phone, $event);
            $this->setError('验证码已失效');
            return false;
        }

        if ($smsInfo->times > $this->maxCheckNums) {
            $this->flush($phone, $event);
            $this->setError('验证码错误数超过最大值');
            return false;
        }
        //判断验证码是否正确
        if ($smsInfo->code != $code) {
            $smsInfo->times = $smsInfo->times + 1;
            $smsInfo->save();
            $this->setError('Captcha error');
            return false;
        }
        $this->flush($phone, $event);
        return true;
    }

    /**
     * 删除手机号某个时间的所有短信验证码
     * @param string $mobile 手机号
     * @param string $event 事件
     * @return void
     */
    private function flush(string $mobile, string $event): void
    {
        Sms::where(['mobile' => $mobile, 'event' => $event])
            ->delete();
    }

    /**
     * 获取事件
     * @param string $event
     * @return bool
     */
    private function getEvent(string $event): bool
    {
        if (!array_key_exists($event, $this->eventList)) {
            $this->setError('Incident does not exist');
            return false;
        }
        return true;
    }

    /**
     * 获取最后一次手机发送的数据
     *
     * @param   int    $mobile 手机号
     * @param   string $event  事件
     * @return  Sms
     */
    public function get($mobile, $event = 'default')
    {
        $sms = Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        return $sms ?: null;
    }
}